package com.fzrskj.cloud.free.user.dao;

import com.fzrskj.cloud.free.core.tool.CObjectTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.user.bean.UserMessage;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wangxinhao
 * @version 2016-10-11
 */
public class UserMessageDao extends CObject {
    //private declarations
    private IDbDrv db = null;

    //constructor function to initialize database access object
    public UserMessageDao() {
        db = CloudDbDrvUtils.getDbUtilsDrv();
    }

    //to free resource
    @Override
    public void dispose() {
        db.closeConnection();
    }

    /**
     * 获取数据消息
     *
     * @param msgTime
     * @return
     */
    public List<UserMessage> getUserMessageList(Date msgTime) {
        Object[] params = {msgTime};
        String sql = "select * from user_message where msgTime = ?";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        List<UserMessage> list = db.queryForBeans(sql, UserMessage.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return list;
    }

    /**
     * 批量删除
     *
     * @param messagesIds
     * @param userName
     * @return
     */
    public int delUserMessage(List<UserMessage> messagesIds, String userName) {
        Object[] params = {userName, messagesIds};
        String sql = "delete user_message where userName=? and id in (:messageIds)";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        int ret = db.executeSql(sql, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return ret;
    }

    /**
     * 标记为已读
     *
     * @param state
     * @param userName
     * @return
     */
    public int upState(int state, String userName) {
        Object[] params = {state, userName};
        String sql = "update user_message set state=1 where id=? and userName=?";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        int ret = db.executeSql(sql, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return ret;
    }

    /**
     * 批量标记已读
     *
     * @param messageIds
     * @param state
     * @return
     */
    public int updStateList(List<UserMessage> messageIds, int state) {
        Object[] params = {state, messageIds};
        String sql = "update user_message set state=1 where userName=? and id in (:messageIds)";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        int ret = db.executeSql(sql, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return ret;
    }

    /**
     * 统计用户未读消息数量
     *
     * @param userName
     * @return
     */
    public List<UserMessage> getUserMessageCount(String userName) {
        Object[] params = {userName};
        String sql = "select count(id) from ser_message where state =2 and userName=?";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        List<UserMessage> list = db.queryForBeans(sql, UserMessage.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return list;
    }

    //to add new record to database by bean
    public int addUserMessage(UserMessage obj) {
        //代理商数据隔离
        obj.setAgentId(CloudContextUtils.getAgentId());
        String sql = "insert into user_message(id,attachmentFile,content,msgTime,msgType,sender," +
                "senderId,state,title,userId,userName,agentId)" +
                "values(?,?,?,?,?,?," +
                "?,?,?,?,?,?);";
        Object[] prm = {obj.getId(), obj.getAttachmentFile(), obj.getContent(), obj.getMsgTime(), obj.getMsgType(), obj.getSender(),
                obj.getSenderId(), obj.getState(), obj.getTitle(), obj.getUserId(), obj.getUserName(), obj.getAgentId()};
        int ret = db.executeSql(sql, prm);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to add new record to database by map
    public int addUserMessage(Map<String, Object> values) {
        //代理商数据隔离
        values.put("agentId", CloudContextUtils.getAgentId());
        int ret = db.insertRecord("user_message", values);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by id
    public int delUserMessage(int id) {
        Object[] params = {id};
        String sql = "delete from user_message where id=?";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());
        int ret = db.executeSql(sql, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by cdt
    public int delUserMessage(Map<String, Object> cdt) {
        //代理商数据隔离
        cdt.put("agentId", CloudContextUtils.getAgentId());

        int ret = db.deleteRecord("user_message", cdt);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to modify table record by values and condition
    public int modUserMessage(Map<String, Object> values, Map<String, Object> cdt) {
        //代理商数据隔离
        cdt.put("agentId", CloudContextUtils.getAgentId());

        int ret = db.modifyRecord("user_message", values, cdt);
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return ret;
    }

    //to query user_message item for detail
    public UserMessage queryUserMessage(int id) {
        Object[] params = {id};
        String sql = "select * from user_message where id=?";

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        UserMessage ret = db.queryForBean(sql, UserMessage.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to query UserMessage record count
    public int queryUserMessage(int uid, int msgType) {
        List<Object> list = new ArrayList<>();
        String sql = "select count(id) from user_message where 1>0 ";

        sql += " and agentId=? ";
        list.add(CloudContextUtils.getAgentId());

        if (uid > 0) {
            sql += "and userId=?";
            list.add(uid);
        }
        if (msgType >= 0) {
            sql += "and msgType=?";
            list.add(uid);
        }
        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        Long ret = (Long) db.queryFieldValue(sql, Long.class, params, 1);
        this.setErrCode(db.getErrCode());
        if (ret == null) {
            return -1;
        }
        return ret.intValue();
    }

    //to query UserMessage for record list with condition,if page or pagesize less than 0, means without page
    public List<UserMessage> queryUserMessageList(int uid, int msgType, int page, int pagesize) {
        List<Object> list = new ArrayList<>();
        String sql = "select count(id) from user_message where 1>0 ";

        sql += " and agentId=? ";
        list.add(CloudContextUtils.getAgentId());

        if (uid > 0) {
            sql += "and userId=?";
            list.add(uid);
        }
        if (msgType >= 0) {
            sql += "and msgType=?";
            list.add(uid);
        }
        sql += "order by msgTime";
        if (page > 0) {
            sql += String.format("like %d, %d", (page - 1) * pagesize, pagesize);
        }
        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        List<UserMessage> ret = db.queryForBeans(sql, UserMessage.class, params);
        this.setErrCode(db.getErrCode());
        return ret;
    }

}